package com.songlanyun.modules.usergains.service.lvcodeimpl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.songlanyun.common.enums.DistributionConstant;
import com.songlanyun.common.enums.GoodsConstant;
import com.songlanyun.common.enums.MemberConstant;
import com.songlanyun.common.enums.OrderConstant;
import com.songlanyun.common.utils.custom.MathUtils;
import com.songlanyun.modules.account.entity.AccountEntity;
import com.songlanyun.modules.account.entity.UserInfoEntity;
import com.songlanyun.modules.account.model.vo.AccountParentVO;
import com.songlanyun.modules.account.service.AccountService;
import com.songlanyun.modules.account.service.UserInfoService;
import com.songlanyun.modules.applyareaagent.entity.ApplyAreaAgentEntity;
import com.songlanyun.modules.applyareaagent.service.ApplyAreaAgentService;
import com.songlanyun.modules.config.dao.YxtTeamRewardConfigDao;
import com.songlanyun.modules.config.dao.YxtUserTeamRateConfigDao;
import com.songlanyun.modules.config.entity.ProfitSharingEntity;
import com.songlanyun.modules.config.entity.YxtTeamRewardConfig;
import com.songlanyun.modules.config.entity.YxtUserTeamRateConfig;
import com.songlanyun.modules.config.service.ProfitSharingService;
import com.songlanyun.modules.distributionconfig.entity.DistributionShopProxyConfig;
import com.songlanyun.modules.distributionconfig.model.value.GiftOneRule;
import com.songlanyun.modules.distributionconfig.service.DistributionShopProxyConfigService;
import com.songlanyun.modules.gains.entity.ShopOrderGains;
import com.songlanyun.modules.order.entity.Order;
import com.songlanyun.modules.order.entity.OrderReceipt;
import com.songlanyun.modules.order.service.OrderService;
import com.songlanyun.modules.sharebenefitconfig.model.PartnerConfig;
import com.songlanyun.modules.sharebenefitconfig.service.CommonwealShareBenefitConfigService;
import com.songlanyun.modules.shop.entity.ShopEntity;
import com.songlanyun.modules.shop.service.ShopService;
import com.songlanyun.modules.usergains.entity.UserOrderGains;
import com.songlanyun.modules.usergains.service.IDistributionHandle;
import com.songlanyun.modules.usergains.service.UserOrderGainsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 普通商品分润
 */
@Service("generalGoodsDistribution")
public class GeneralGoodsDistributionHandle implements IDistributionHandle {


    @Autowired
    private AccountService accountService;

    @Autowired
    private ShopService shopService;

    @Autowired
    private UserOrderGainsService userOrderGainsService;

    @Autowired
    private ProfitSharingService profitSharingService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private ApplyAreaAgentService applyAreaAgentService;

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private YxtUserTeamRateConfigDao yxtUserTeamRateConfig;


    //普通商品分润记录
    @Override
    public List<UserOrderGains> handle(ShopOrderGains shopOrderGains) {
        List<UserOrderGains> list = new ArrayList<>();
        List<AccountParentVO> vos = accountService.getAllParentUser(shopOrderGains.getUserId());   //获取上级用户
        ProfitSharingEntity profitSharing = profitSharingService.info();  //获取分润配置
        List<YxtUserTeamRateConfig> teamConfig = yxtUserTeamRateConfig.selectList
                (new LambdaQueryWrapper<YxtUserTeamRateConfig>().eq(YxtUserTeamRateConfig::getType,"team").orderByAsc(YxtUserTeamRateConfig::getId));
        //此处获取团队等级分润配置
        List<YxtUserTeamRateConfig> teamRateConfig = this.getListTeamConfig(teamConfig);   //将团队配置按等级排序
        BigDecimal maxWithdrawRate = teamRateConfig.get(teamRateConfig.size()-1).getTeamWithdrawRate();   //当前团队奖励可以给出的最大分润比例
        BigDecimal nowWithdrawRate = BigDecimal.valueOf(0);   //当前团队奖励已经分润的比例
        //---------------
        int equalityIndex = 0;  //平级奖励已分配次数
        int equalityMax = Integer.parseInt(profitSharing.getTerritorial().toString());  //平级奖励最大分配次数
        int equalityRate = Integer.parseInt(profitSharing.getInterimHead().toString());  //平级奖励分润比例
        int nowMaxLevel = 0;  //当前团队奖励获得的最大等级
        int index = 0;
        for (AccountParentVO vo : vos) {
            index ++;
            if(!vo.getActivating()){
                continue;
            }
            if(index > 1 && vo.getTeamGrade()<=0){
                continue;
            }
            //获取本次循环的用户等级分润比例
            BigDecimal userLevelRate = teamRateConfig.get(vo.getTeamGrade()).getTeamWithdrawRate();
            if(index==1) {
                //计算直推奖励   根据订单总价格按比例计算
                BigDecimal gains = MathUtils.setScale(shopOrderGains.getTotalRealPrice().doubleValue() * profitSharing.getPushStraight().doubleValue() / 100);
                if(gains.compareTo(BigDecimal.ZERO)>0) {
                    UserOrderGains userOrderGains = userOrderGainsService.createGains(shopOrderGains, buildUserOrderGainsTo(vo,
                            DistributionConstant.DistributionComputer.COMMON,
                            DistributionConstant.DistributionType.COMMON_ONE_LEVEL,
                            gains,
                            profitSharing.getPushStraight(),
                            "分享获得"));
//                    if(GoodsConstant.AreaFeature.ACTIVATING.equals(shopOrderGains.getAreaFeature())) {
//                        BigDecimal balanceGains = MathUtils.setScale(shopOrderGains.getGains().doubleValue() * profitSharing.getWelfarePushStraight().doubleValue() / 100);
//                        userOrderGains.setBalanceGains(balanceGains);
//                        userOrderGains.setBalanceRatio(profitSharing.getWelfarePushStraight());
//                        userOrderGainsService.modify(userOrderGains);
//                    }
                    list.add(userOrderGains);
                }
                System.out.println("直推分享获得："+gains+"用户id"+vo.getId()+"奖励比例"+profitSharing.getPushStraight());
                continue;
            }else{
                //这里计算团队和平级奖励
                if(maxWithdrawRate == nowWithdrawRate && equalityIndex == equalityMax){   //如果没有剩余分润比例 而且平级奖励也分配完  直接跳出
                    break;
                }
                //如果当前用户的团队等级大于等于当前最大等级   代表能获得团队或是平级奖励
                if(vo.getTeamGrade() >= nowMaxLevel){
                    if(vo.getTeamGrade() > nowMaxLevel){
                        //计算当前等级可以分润的剩余比例
                        BigDecimal sendWithdrawRate = userLevelRate.subtract(nowWithdrawRate);
                        if(sendWithdrawRate.compareTo(new BigDecimal(0)) < 1){
                            continue;
                        }else{
                            maxWithdrawRate = maxWithdrawRate.subtract(sendWithdrawRate);   //当前等级分润完毕  减去已经分润的比例
                            nowMaxLevel = vo.getTeamGrade();  //当前用户等级重置为当前最大等级
                            //分润执行代码
                            BigDecimal headOfGroup = MathUtils.setScale(shopOrderGains.getTotalRealPrice().doubleValue() * sendWithdrawRate.doubleValue() / 100);
                            if(headOfGroup.compareTo(BigDecimal.ZERO)>0) {
                                UserOrderGains userOrderGains = userOrderGainsService.createGains(shopOrderGains, buildUserOrderGainsTo(vo,
                                        DistributionConstant.DistributionComputer.DIRECT_GROUP_LEADER,
                                        DistributionConstant.DistributionType.DIRECT_GROUP_LEADER,
                                        headOfGroup,
                                        profitSharing.getHeadOfGroup(),
                                        "团队奖励"));
                                list.add(userOrderGains);
                            }
                            //----------------
                        }
                    }
                    if(vo.getTeamGrade() == nowMaxLevel){  //平级计算
                        if(equalityIndex == equalityMax){
                            continue;  //如果平级奖励已经分配完  跳过
                        }else{   //分配平级奖励
                            equalityIndex++;  //平级奖励分配次数加一
                            //执行平级分润代码
                            BigDecimal gains = MathUtils.setScale(shopOrderGains.getTotalRealPrice().doubleValue() * equalityRate / 100);
                            if(gains.compareTo(BigDecimal.ZERO)>0) {
                                UserOrderGains userOrderGains = userOrderGainsService.createGains(shopOrderGains, buildUserOrderGainsTo(vo,
                                        DistributionConstant.DistributionComputer.INDIRECT_GROUP_LEADER,
                                        DistributionConstant.DistributionType.INDIRECT_GROUP_LEADER,
                                        gains,
                                        profitSharing.getInterimHead(),
                                        "平级奖励"));
                                list.add(userOrderGains);
                            }
                            System.out.println("平级奖励获得："+gains+"用户id"+vo.getId()+"奖励比例"+equalityRate);
                        }
                    }
                }else{
                    continue;
                }
            }
        }

        //区域代理的分润   当前版本暂时不用
        Long orderId = shopOrderGains.getOrderId();
        Order order = orderService.getById(orderId);
        OrderReceipt receipt = order.loadOrderReceipt();
        ApplyAreaAgentEntity entity = applyAreaAgentService.loadBy(receipt.getProvinceCode(), receipt.getCityCode(), receipt.getAreaCode());
        if(ObjectUtil.isNotNull(entity)) {
            AccountEntity user = accountService.getUserById(entity.getUserId(), false);
            UserInfoEntity userInfoEntity = userInfoService.loadById(entity.getUserId(), false);
            if(ObjectUtil.isNotNull(user)) {
                AccountParentVO vo = new AccountParentVO();
                vo.setId(entity.getUserId());
                vo.setMobile(user.getMobile());
                vo.setUsername(StringUtils.isNotEmpty(userInfoEntity.getRealName())?userInfoEntity.getRealName():userInfoEntity.getNickname());
                BigDecimal gains = MathUtils.setScale(shopOrderGains.getTotalConsumptionValue().doubleValue() * profitSharing.getTerritorial().doubleValue() / 100);


                if(gains.compareTo(BigDecimal.ZERO)>0) {
                    UserOrderGains userOrderGains = userOrderGainsService.createGains(shopOrderGains, buildUserOrderGainsTo(vo,
                            DistributionConstant.DistributionComputer.AREA_AGENT,
                            DistributionConstant.DistributionType.AREA_AGENT,
                            gains,
                            profitSharing.getPushStraight(),
                            "线上订单属地分润"));
                    System.err.println(list);
                    if (GoodsConstant.AreaFeature.ACTIVATING.equals(shopOrderGains.getAreaFeature())) {
                        BigDecimal balanceGains = MathUtils.setScale(shopOrderGains.getGains().doubleValue() * profitSharing.getWelfareTerritorial().doubleValue() / 100);
                        userOrderGains.setBalanceGains(balanceGains);
                        userOrderGains.setBalanceRatio(profitSharing.getWelfareTerritorial());
                        userOrderGainsService.modify(userOrderGains);
                    }


                    list.add(userOrderGains);
                }
            }
        }
        System.err.println(list);
        return list;
    }


    public List<YxtUserTeamRateConfig> getListTeamConfig(List<YxtUserTeamRateConfig> list){
        List<YxtUserTeamRateConfig> returnList = new ArrayList<>();
        for(int i = 0; i<=list.size(); i++){
            returnList.set(Math.toIntExact(list.get(i).getId()), list.get(i));
        }
        return returnList;
    }

}
